package com.activity.content;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.login.R;
import com.tools.Address;
import com.tools.CommonThings;
import com.tools.CountDownTimer;
import com.tools.NodeView;
import com.tools.OkHttp3;
import com.tools.PayDialog;
import com.tools.seckillgoods.SecKillGoods;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.Response;

public class SecGoodsDetail extends AppCompatActivity {
    private ImageView back, refresh;
    private LinearLayout scrollLinear;
    //产品相关属性
    private TextView name, risk, rate, minAmount, increaseAmount, term, price, stock, appointText;
    //倒计时相关
    private TextView stateText, dayText, dayTian;
    private CountDownTimer countDownTimer;
    private long countTime;

    private Button deposit;
    private SecKillGoods secGoods;
    private JSONObject detailJSON;
    private int state; //活动状态--0：未开始；1：进行中；2：已结束
    private boolean isAppoint = false;

    private boolean isBuy = false;

    private NodeView nodeView;
    private List<String> titleList = new ArrayList<>();
    private List<String> nodeList = new ArrayList<>();

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what){
                case 0x001:

                    break;
                case 0x002:
                    if (!isAppoint){
                        appointText.setText("点击预约");
                    }
                    break;
            }
            return false;
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sec_detail);
        initView();
        secGoods = getIntent().getParcelableExtra("secGoods");
        setData(secGoods);

        titleList.add("");
        titleList.add(tranTime(secGoods.getStartDate()));
        titleList.add(tranTime(secGoods.getValueDate()));
        titleList.add(tranTime(secGoods.getEndDate()));
        titleList.add(tranTime(secGoods.getDueDate()));
        titleList.add("");

        nodeList.add("");
        nodeList.add("秒杀日");
        nodeList.add("起息日");
        nodeList.add("秒杀结束");
        nodeList.add("结息日");
        nodeList.add("");

        nodeView.setTitleList(titleList);
        nodeView.setNodeList(nodeList);
        try {
            nodeView.setSelectIndex(getSelectIndex());
        } catch (ParseException e) {
            e.printStackTrace();
        }


        try {
            state = getState();
        } catch (ParseException e) {
            e.printStackTrace();
        }

        try {
            initCountTimer();
        } catch (ParseException e) {
            e.printStackTrace();
        }

        getAppointMap();

        back.setOnClickListener(view ->{
            finish();
        });

        refresh.setOnClickListener(view ->{
            getAppointMap();
            Toast.makeText(SecGoodsDetail.this, "刷新成功", Toast.LENGTH_SHORT).show();
        });

        deposit.setOnClickListener(view ->{
            initDialog();
        });

        appointText.setOnClickListener(view ->{
            if (appointText.getText().toString().equals("点击预约")){
                appointText.setText("预约成功");
                Toast.makeText(SecGoodsDetail.this, "预约成功", Toast.LENGTH_SHORT).show();
//                getGoodsAppoint();
            }
        });

        while (countDownTimer.isEnd){
            int day = Integer.parseInt(dayText.getText().toString());
            if (day > 0){
                day -= 1;
                dayText.setText(String.valueOf(day));
                countDownTimer.init(86400000, 1000);
                countDownTimer.updateTimer();
            }else {
                if (state == 0) {
                    //开始倒计时结束，开始秒杀
                    state = 1;
                    try {
                        countTime = setCountdown(secGoods.getEndDate());
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    stateText.setText("距离活动结束还有");
                    deposit.setEnabled(true);
                    dayText.setText(String.valueOf(countTime / 86400000));
                    countDownTimer.init(countTime % 86400000, 1000);
                    countDownTimer.updateTimer();
                }else if (state == 1){
                    state = 2;
                    deposit.setEnabled(false);
                    stateText.setText("秒杀已结束");
                    dayText.setVisibility(View.GONE);
                    dayTian.setVisibility(View.GONE);
                    countDownTimer.setVisibility(View.GONE);
                }
            }
        }
    }

    private void initView(){
        scrollLinear = findViewById(R.id.sec_detail_scroll_linear);
        back = findViewById(R.id.sec_detail_back);
        refresh = findViewById(R.id.sec_detail_refresh);
        name = findViewById(R.id.sec_detail_name);
        risk = findViewById(R.id.sec_detail_risk);
        rate = findViewById(R.id.sec_detail_rate);
        minAmount = findViewById(R.id.sec_detail_min_amount);
        increaseAmount = findViewById(R.id.sec_detail_increase_amount);
        term = findViewById(R.id.sec_detail_term);
        deposit = findViewById(R.id.sec_detail_deposit);
        price = findViewById(R.id.sec_detail_price);
        stock = findViewById(R.id.sec_detail_stock);
        appointText = findViewById(R.id.sec_detail_appoint);

        dayText = findViewById(R.id.sec_detail_time_day);
        dayTian = findViewById(R.id.sec_detail_time_day_text);
        stateText = findViewById(R.id.sec_detail_time_state);
        countDownTimer = findViewById(R.id.sec_detail_time_count_timer);

        nodeView = findViewById(R.id.sec_detail_node_view);

        View view = View.inflate(SecGoodsDetail.this, R.layout.detail_tips, null);
        scrollLinear.addView(view);
    }

    //初始化CountDownTimer
    private void initCountTimer() throws ParseException {
        if (state == 0){ //活动未开始
            countTime = setCountdown(secGoods.getStartDate());
            deposit.setEnabled(false);
            dayText.setText(String.valueOf(countTime / 86400000));
            countDownTimer.init(countTime % 86400000, 1000);
            countDownTimer.updateTimer();
        }else if (state == 1){ //活动进行中
            countTime = setCountdown(secGoods.getEndDate());
            stateText.setText("距离活动结束还有");
            deposit.setEnabled(true);
            dayText.setText(String.valueOf(countTime / 86400000));
            countDownTimer.init(countTime % 86400000, 1000);
            countDownTimer.updateTimer();
        }else if (state == 2){ //活动已结束
            stateText.setText("活动已结束");
            deposit.setEnabled(false);
            dayText.setVisibility(View.GONE);
            dayTian.setVisibility(View.GONE);
            countDownTimer.setVisibility(View.GONE);
        }
    }

    private void setData(SecKillGoods secGoods){
        name.setText(secGoods.getName());

        risk.setText(CommonThings.getRiskGrade(secGoods.getRiskGrade()));
        if (secGoods.getRiskGrade() == 1){
            risk.setBackgroundResource(R.color.sign_warn);
        }else if (secGoods.getRiskGrade() == 2){
            risk.setBackgroundResource(R.color.warn);
        }

        rate.setText(CommonThings.invertPercent(secGoods.getAnnualInterestRate()));
        minAmount.setText(String.format(SecGoodsDetail.this.getResources().getString(R.string.minAmount), secGoods.getMinAmount()));
        increaseAmount.setText(String.format(SecGoodsDetail.this.getResources().getString(R.string.increaseAmount), secGoods.getIncreasingAmount()));
        term.setText(String.format(SecGoodsDetail.this.getResources().getString(R.string.productDeadline), secGoods.getProductDeadline()));

        price.setText(String.format(SecGoodsDetail.this.getResources().getString(R.string.secKill_price), secGoods.getSecKillPrice()));
        stock.setText(String.format(SecGoodsDetail.this.getResources().getString(R.string.secKill_stock), secGoods.getSecKillStock()));
    }

    private void initDialog(){
        PayDialog payDialog = new PayDialog(SecGoodsDetail.this);
        payDialog.setGoodsVis(false);
        payDialog.setInputVis(true);
        payDialog.setOnPayClickListener(new PayDialog.OnPayClickListener() {
            @Override
            public void onPayClick() {
                if (isBuy){
                    Toast.makeText(SecGoodsDetail.this, "每人限购一份", Toast.LENGTH_SHORT).show();
                }else{
                    if (payDialog.getInputText().length() < 6)
                        Toast.makeText(SecGoodsDetail.this, "请输入正确密码", Toast.LENGTH_SHORT).show();
                    else {
                        payDialog.dismiss();
                        isBuy = true;
                        deposit.setEnabled(false);
                        Toast.makeText(SecGoodsDetail.this, "购买成功", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });

        payDialog.setOnCancelClickListener(new PayDialog.OnCancelClickListener() {
            @Override
            public void onCancelClick() {
                payDialog.dismiss();
            }
        });
        payDialog.show();
    }

    private void getGoodsDetail(String id){
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), id);

        OkHttp3.sendOkHttpPostTokenRequest(Address.getSecGoodsDetail(), body, CommonThings.tokenValue, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(SecGoodsDetail.this, "服务器连接失败",Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                detailJSON = JSONObject.parseObject(res);
                Log.d("goodsDetail", detailJSON.toString());
                if (detailJSON.getString("code").charAt(0) == '2'){
                    handler.sendEmptyMessage(0x001);
                }else if(detailJSON.getString("code").charAt(0) == '5'){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(SecGoodsDetail.this, detailJSON.getString("message"), Toast.LENGTH_SHORT).show();
                        }
                    });
                }else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(SecGoodsDetail.this, "连接出错了", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        });
    }

    private void getGoodsAppoint(){
        JSONObject appointBody = new JSONObject();
        appointBody.put("userId", CommonThings.userId);
        appointBody.put("seckillGoodsId", secGoods.getSecKillGoodsId());
        Log.d("appointBody", appointBody.toString());

        RequestBody body = RequestBody.create(MediaType.parse("text/plain"), appointBody.toJSONString());
        OkHttp3.sendOkHttpPostTokenRequest(Address.getAppointMent(), body, CommonThings.tokenValue, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(SecGoodsDetail.this, "服务器连接失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                JSONObject responseJSON = JSONObject.parseObject(res);
                Log.d("setAppoint", responseJSON.toString());
                if (responseJSON.getString("code").charAt(0) == 2){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            appointText.setText(responseJSON.getString("data"));
                        }
                    });
                }else if (responseJSON.getString("code").charAt(0) == 5){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(SecGoodsDetail.this, responseJSON.getString("message"), Toast.LENGTH_SHORT).show();
                        }
                    });
                }else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(SecGoodsDetail.this, "网络连接出错了", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        });
    }

    private void getAppointMap(){
        JSONObject jsonObject = new JSONObject();
        JSONObject pageJson = new JSONObject();
        JSONObject sortJson = new JSONObject();
        JSONObject queryJson = new JSONObject();
        pageJson.put("current", "1");
        pageJson.put("size", "20");
        queryJson.put("userId", CommonThings.userId);

        jsonObject.put("page", pageJson);
        jsonObject.put("sort", sortJson);
        jsonObject.put("query", queryJson);
        RequestBody body = RequestBody.create(MediaType.parse("text/plain; charset=utf-8"), jsonObject.toJSONString());

        OkHttp3.sendOkHttpPostTokenRequest(Address.getAppointList(), body, CommonThings.tokenValue, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(SecGoodsDetail.this,"服务器连接失败",Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                JSONObject listJSON = JSONObject.parseObject(res);
                Log.d("appointList", listJSON.toString());
                if (listJSON.getString("code").charAt(0) == '2'){
                    JSONArray itemArray = listJSON.getJSONObject("data").getJSONArray("items");
                    for (int i=0; i<itemArray.size(); i++){
                        JSONObject itemJSON = itemArray.getJSONObject(i);
                        if (itemJSON.getString("goodsName").equals(secGoods.getName())){
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    appointText.setText(CommonThings.getAppoint(itemJSON.getInteger("result")));
                                }
                            });
                            isAppoint = true;
                        }
                    }
                    handler.sendEmptyMessage(0x002);
                }else if (listJSON.getString("code").charAt(0) == '5'){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(SecGoodsDetail.this, listJSON.getString("message"),Toast.LENGTH_SHORT).show();
                        }
                    });
                }else{
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(SecGoodsDetail.this, "连接出错了",Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        });
    }

    //获取系统时间与秒杀时间之差
    private long setCountdown(String secDate) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(System.currentTimeMillis());
        long NTime = simpleDateFormat.parse(simpleDateFormat.format(date)).getTime();
        long OTime = simpleDateFormat.parse(secDate).getTime();
        return (OTime - NTime);
    }

    private int getState() throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(System.currentTimeMillis());
        Log.d("secDate", date.toString());
        Date startDate = formatter.parse(secGoods.getStartDate());
        Date endDate = formatter.parse(secGoods.getEndDate());
        if (date.before(startDate)){
            return 0;
        }else if (date.after(endDate)){
            return 2;
        }else {
            return 1;
        }
    }

    private String tranTime(String time){
        return time.substring(0,10).replace("-", "/");
    }

    private int getSelectIndex() throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date(System.currentTimeMillis());
        Date startDate = formatter.parse(secGoods.getStartDate());
        Date endDate = formatter.parse(secGoods.getEndDate());
        Date valueDate = formatter.parse(secGoods.getValueDate());
        Date dueDate = formatter.parse(secGoods.getDueDate());

        if (date.before(startDate)){
            return 0;
        }else if (date.equals(startDate) || (date.after(startDate) && date.before(valueDate))){
            return 1;
        }else if (date.equals(valueDate) || (date.after(valueDate) && date.before(endDate))){
            return 2;
        }else if (date.equals(endDate) || (date.after(endDate) && date.before(dueDate))){
            return 3;
        }else if (date.equals(dueDate)){
            return 4;
        }else if (date.after(dueDate)){
            return 5;
        }
        return 0;
    }
}